<template>
  <div class="new-page" :style="`min-height: ${pageMinHeight}px`">
    <navbar title="修改角色" @back="resetForm"/>
    <div class="form_box">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        style="max-width: 700px"
      >
        <a-form-model-item ref="name" label="角色名称" prop="name">
          <a-input
            v-model="form.name"
            placeholder="请输入角色名称"
            @blur="
              () => {
                $refs.name.onFieldBlur();
              }
            "
          />
        </a-form-model-item>
        <a-form-model-item label="角色描述">
          <a-input v-model="form.description" placeholder="请输入角色描述" />
        </a-form-model-item>
        <a-form-model-item label="权限模块">
          <a-tree
            v-model="checkedKeys"
            checkable
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            @expand="onExpand"
            @select="onSelect"
          />
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button @click="resetForm"> 取消 </a-button>
          <a-button style="margin-left: 10px" type="primary" @click="onSubmit">
            保存
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { get, updata,gets,add } from "@/services";
export default {
  name: "addUser",
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      other: "",
      form: {},
      rules: {
        name: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur",
          },
        ],
      },
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
    };
  },
  watch: {
    checkedKeys(val) {
      console.log("onCheck", val);
    },
  },
  computed: {
    ...mapState("setting", ["pageMinHeight"]),
  },
  created() {
      gets({ limit: 999 },'permissions').then(({ data }) => {
        if (data.code == 20000) {
          let info = [];
          data.data.data.forEach((element) => {
            let arr = element.name.split(":");
            let i = info.findIndex((e) => e.title == arr[0]);
            if (i != -1) {
              info[i].children.push({ title: arr[1], key: element.id });
            } else {
              if(arr[1]){
                info.push({
                  title: arr[0],
                  key: `${arr[0]}-clear`,
                  children: [{ title: arr[1], key: element.id }],
                });
              }else{
                info.push({
                  title: arr[0],
                  key: element.id,
                  children: [],
                })
              }
            }
          });
          this.treeData = info;
        }
      });
    let id = this.$route.query.id;
    if (!id) {
      return;
    }
    get(id,'roles').then(({ data }) => {
      if (data.code == 20000) {
        let res = data.data;
        setTimeout(() => {
          this.checkedKeys = res.permissions.map((e) => e.id);
        }, 500);
        this.form = {
          name: res.name,
          description: res.description,
          id: res.id,
        };
      }
    });
    
  },
  methods: {
    onSubmit() {
      let _this = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
            let fun =_this.form.id?updata:add
          let ids = _this.checkedKeys.filter(
            (e) => `${e}`.indexOf("clear") == -1
          );
          fun({ ..._this.form, permissions: ids },'roles').then(({ data }) => {
            if (data.code == 20000) {
              _this.resetForm();
            } else {
              _this.$message.error("修改角色失败");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.$router.push("/user");
    },
    onExpand(expandedKeys) {
      console.log("onExpand", expandedKeys);
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys) {
      this.selectedKeys = selectedKeys;
    },
  },
};
</script>

<style scoped lang="less">
.new-page {
  height: 100%;
  background-color: @base-bg-color;
  border-radius: 4px;
  .form_box {
    padding: 24px;
  }
}
</style>